package drds.configuration.db.xml_mapping.sql_execute;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MapListBuilder {

    public static final List<Map<String, Object>> build(ResultSet resultSet) throws SQLException {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        // 数据库字段顺序<以此为标准>和数组下标要保持一致
        String[] columnLabels = new String[columnCount + 1];
        int[] types = new int[columnCount + 1];
        //
        buildColumnLabelsAndTypes(resultSetMetaData, columnLabels, types);
        while (resultSet.next()) {
            Map<String, Object> map = new HashMap<String, Object>();
            for (int i = 1; i <= columnCount; i++) {
                Object value;
                // 根据字段的类型的Enum类型取值
                if (types[i] < Types.BLOB) {
                    value = resultSet.getObject(i);
                } else {
                    throw new RuntimeException("else");
                }
                map.put(columnLabels[i], value);
            }
            mapList.add(map);
        }
        return mapList;
    }

    private static final void buildColumnLabelsAndTypes(ResultSetMetaData resultSetMetaData, String[] labelNames, int[] types) throws SQLException {
        int length = labelNames.length;
        if (length == 0) {
            throw new IllegalArgumentException("表字段个数为0");
        }
        for (int i = 1; i <= length - 1; i++) {
            labelNames[i] = resultSetMetaData.getColumnLabel(i);
            types[i] = resultSetMetaData.getColumnType(i);
        }
    }
}
